<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>交易记录</p>
    </header>
    <div class="content">
      <div class="filters">
        <input type="date" v-model="start" />
        <input type="date" v-model="end" />
        <select v-model="type">
          <option value="">全部类型</option>
          <option v-for="t in types" :key="t" :value="t">{{ typeName(t) }}</option>
        </select>
        <button @click="applyFilters">筛选</button>
        <button @click="exportCsv">导出CSV</button>
      </div>
      <ul class="list">
        <li v-for="t in displayList" :key="t.id" class="item">
          <div class="left">
            <div class="type">{{ typeName(t.type) }}</div>
            <div class="sub">交易号 {{ t.transactionNo }}</div>
            <div class="sub">订单 {{ t.orderId || '-' }}</div>
            <div class="sub">费用 ¥{{ formatAmount(t.fee) }} 奖励 ¥{{ formatAmount(t.rewardAmount) }}</div>
          </div>
          <div class="right" :class="amountClass(t.amount)">¥{{ formatAmount(t.amount) }}</div>
        </li>
      </ul>
      <div class="pagination">
        <button :disabled="page<=0" @click="prev">上一页</button>
        <span>第 {{ page+1 }} / {{ totalPages }} 页</span>
        <button :disabled="page>=totalPages-1" @click="next">下一页</button>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi } from '../api'

const router = useRouter()
const page = ref(0)
const size = ref(10)
const totalPages = ref(1)
const items = ref([])
const start = ref('')
const end = ref('')
const type = ref('')
const types = ['DEPOSIT','WITHDRAW','PAYMENT','TRANSFER_IN','TRANSFER_OUT','FREEZE','UNFREEZE','REFUND','REALIZE_INCOME']

const loadPage = async () => {
  const res = await walletApi.listTransactions({ page: page.value, size: size.value })
  items.value = Array.isArray(res?.content) ? res.content : []
  totalPages.value = Number(res?.totalPages || 1)
}

const applyFilters = async () => {
  if (start.value && end.value) {
    const res = await walletApi.listTransactionsByPeriod({ startDate: start.value, endDate: end.value })
    items.value = Array.isArray(res) ? res : []
    totalPages.value = 1
    page.value = 0
  } else {
    await loadPage()
  }
}

onMounted(loadPage)

const displayList = computed(() => {
  const base = items.value.filter(x => x.type !== 'FREEZE_INCOME')
  if (!type.value) return base
  return base.filter(x => x.type === type.value)
})

const prev = async () => { if (page.value>0) { page.value--; await loadPage() } }
const next = async () => { if (page.value<totalPages.value-1) { page.value++; await loadPage() } }
const goBack = () => router.push('/wallet')
const formatAmount = v => Number(v || 0).toFixed(2)
const amountClass = v => Number(v) >= 0 ? 'pos' : 'neg'
const typeName = t => {
  const map = {
    DEPOSIT:'充值', 
    WITHDRAW:'提现', 
    PAYMENT:'支付', 
    TRANSFER_IN:'转入', 
    TRANSFER_OUT:'转出', 
    FREEZE:'冻结', 
    UNFREEZE:'解冻', 
    REFUND:'退款', 
    REALIZE_INCOME:'已实现收益',
    OVERDRAFT_REPAY:'花呗还款',
    OVERDRAFT_REPAYMENT:'花呗还款',
    OVERDRAFT_PAY:'花呗支付'
  }
  return map[t] || t
}

const exportCsv = () => {
  const rows = [['交易号','类型','金额','费用','奖励','订单','时间']]
  displayList.value.forEach(x => {
    rows.push([x.transactionNo, typeName(x.type), Number(x.amount||0), Number(x.fee||0), Number(x.rewardAmount||0), x.orderId||'', x.createTime||''])
  })
  const csv = rows.map(r => r.join(',')).join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'transactions.csv'
  a.click()
  URL.revokeObjectURL(url)
}
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100%; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.content { margin-top: 14vw; padding: 4vw; }
.filters { display: flex; gap: 3vw; margin-bottom: 3vw; }
.list { list-style: none; margin: 0; padding: 0; }
.item { display: flex; justify-content: space-between; align-items: center; padding: 3vw 0; border-bottom: 1px solid #eee; }
.left .type { font-size: 4vw; color: #333; }
.left .sub { font-size: 3vw; color: #999; }
.right { font-size: 4vw; font-weight: 700; }
.right.pos { color: #38ca73; }
.right.neg { color: #ff6b35; }
.pagination { display: flex; justify-content: center; align-items: center; gap: 4vw; margin-top: 4vw; }
</style>
